import React, { Component } from 'react';
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { WingBlank, WhiteSpace, ListView  } from 'antd-mobile';
import * as common from 'common/common.js';
import './bookFree.less';

class BookFree extends Component{

  constructor(props) {
      super(props);
      this.lv = null;
      this.fetchData = [];
      const ds = new ListView.DataSource({
          rowHasChanged: (row1, row2) => row1 !== row2,
      });
      
      if(common.cacheExists("cacheList")){
        this.fetchData = [...this.fetchData, ...common.cacheGet("cacheList")];
        this.state = {
            pageNo: common.cacheGet("cachePageNo"),
            ds: ds,
            isLoading: true,
            hasMore: true,
            height: document.documentElement.clientHeight * 3 / 4
        }
      }else{
        this.state = {
            pageNo: 0,
            ds: ds,
            isLoading: true,
            hasMore: true,
            height: document.documentElement.clientHeight * 3 / 4
        }
      }
  }
  
  refreshData = (pageNo) => {
      return [
      {
        img: 'https://zos.alipayobjects.com/rmsportal/dKbkpPXKfvZzWCM.png',
        title: 'Meet hotel',
        des: '当前翻页所处位置：'+pageNo+" 排序0",
      },
      {
        img: 'https://zos.alipayobjects.com/rmsportal/XmwCzSeJiqpkuMB.png',
        title: 'McDonald\'s invites you',
        des: '当前翻页所处位置：'+pageNo+" 排序1",
      },
      {
        img: 'https://zos.alipayobjects.com/rmsportal/hfVtzEhPzTUewPm.png',
        title: 'Eat the week',
        des: '当前翻页所处位置：'+pageNo+" 排序2",
      },
    ]
    }

    componentDidMount() {
      const height = document.documentElement.clientHeight;
      if(common.cacheExists("cachePosition")){
      setTimeout(() => {
          this.setState({
            ds: this.state.ds.cloneWithRows(this.fetchData),
            isLoading: false,
            height: height
          });
        }, 600);
        console.log(height)
        console.log("++++"+common.cacheGet("cachePosition"))
//        setTimeout(() => this.lv.scrollTo(0, 4000), 600);
      }else{
        setTimeout(() => {
          let data = this.refreshData(this.state.pageNo);
          this.fetchData = [...this.fetchData, ...data];
          this.setState({
            ds: this.state.ds.cloneWithRows(this.fetchData),
            isLoading: false,
            height: height,
            pageNo: this.state.pageNo+1
          });
        }, 600);
      }
    }
    
    renderItem = (rowData) => {
      return (
        <div>
          <div style={{height: '4rem'}}>{rowData.des}</div>
        </div>
      )
  }
    
  onEndReached = (event) => {
    console.log("onEndReached")
      if (this.state.isLoading && !this.state.hasMore) {
        return;
      }
      
      this.setState({ 
        isLoading: true 
      });
      setTimeout(() => {
        let data = this.refreshData(this.state.pageNo);
        this.fetchData = [...this.fetchData, ...data];
          this.setState({
            ds: this.state.ds.cloneWithRows(this.fetchData),
            isLoading: false,
            pageNo: this.state.pageNo+1
          });
          
          //保存当前浏览数据到缓存中
          common.cacheSet("cacheList", this.fetchData);
          common.cacheSet("cachePageNo", this.state.pageNo);
      }, 500);
    }
  
  onScroll = (event) => {
    var scrollTop = this.lv.refs.listview.refs.listviewscroll.refs.ScrollView.scrollTop;
//    const scrollTop = event.target.scrollTop
    common.cacheSet("cachePosition", scrollTop);
    console.log(scrollTop)

  }

  componentWillUnmount(){
    console.log(this.props.userinfo.prevRouteUrl)
  }

  scrollControl = () => {
    sessionStorage.clear();
  }

  render(){
    return(
      <div className="container bookFree">
        <div style={{height:'1rem',width:'1rem',position:'fixed',right:0,top:'0rem',backround:'#aaa',zIndex:'1000000'}}
          onClick={this.scrollControl}>Click Me</div>
        <WingBlank>
          <ListView
            className="bookFreeList"
                ref={el => this.lv = el}
                dataSource={this.state.ds}
                renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                  {this.state.isLoading ? 'Loading...' : 'Loaded'}
                </div>)}
                renderRow={this.renderItem}
                style={{
                  height: this.state.height,
                  overflow: 'auto',
                }}
                pageSize={3}
                onScroll={this.onScroll}
                scrollRenderAheadDistance={500}
                onEndReached={this.onEndReached}
                onEndReachedThreshold={10}
              />
            </WingBlank>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    userinfo: state.userinfo
  }
}

function mapDispatchToProps(dispatch){
  return {}
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BookFree);